<template>
    <div class="excel">
        <el-upload class="upload-demo" drag multiple :on-change="handleChange" :auto-upload="false">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                拖拽到此或者<em>点击上传文件</em>
            </div>
        </el-upload>

        <el-table :data="dataList" style="width: 100%" v-if="dataList.length > 0" border>
            <template v-for="(x, y) in columnList" :key="y">
                <el-table-column :prop="x.name" :label="x.title" width="200" align="center" />
            </template>
        </el-table>
    </div>
</template>
<script setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { ref } from 'vue';
import * as XLSX from 'xlsx';

const word = 'abcdefghijklmnopqrstuvwxyz'
function arrToObj(arr) {
    const obj = []
    arr.map((x, y) => {
        obj[word[y]] = x
    })
    return obj
}
const columnList = ref([])
const dataList = ref([])
function handleChange(res) {
    const reader = new FileReader();
    reader.onload = function (e) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
        const worksheet = workbook.Sheets[sheetName]; // 获取工作表数据
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // 转换为JSON数据，header: 1 表示第一行作为标题行
        // data.value = jsonData; // 更新data引用，以便在模板中显示数据
        // console.log(jsonData)
        let columns = []
        let tableData = []
        jsonData[0].map((x, y) => {
            columns.push({
                name: word[y],
                title: x
            })
        })
        jsonData.map((x, y) => {
            if (y > 0) {
                tableData.push(arrToObj(x))
            }
        })
        columnList.value = columns
        dataList.value = tableData
    };
    reader.readAsArrayBuffer(res.raw);
}
</script>
<style scoped lang="scss"></style>
